﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Planer.Model
{
    public class PeriodicalActionTransactionModel
    {
        static PeriodicalActionTransactionModel model = null;

        protected PeriodicalActionTransactionModel()
        {            
        }

        public static PeriodicalActionTransactionModel GetInstance()
        {
            if (model == null)
            {
                model = new PeriodicalActionTransactionModel();
            }

            return model;
        }

        public periodical_action_transanction GetLastTransactionByPeriodicalAction(periodical_action Action)
        {
            var query = from trans in Program.Db.periodical_action_transanction
                         where trans.periodical_action.id == Action.id
                         orderby trans.create_date descending
                         select trans;
            if (query.Count<periodical_action_transanction>() == 0)
                return null;
            return query.First<periodical_action_transanction>();
                        
        }

        public List<periodical_action_transanction> GetTransactionListByPeriodicalAction(periodical_action Action)
        {
            period p = PeriodModel.GetInstance().GetCurrentPeriod();
            var query = from trans in Program.Db.periodical_action_transanction
                        where trans.periodical_action.id == Action.id
                            && trans.period.id == p.id
                        orderby trans.create_date descending
                        select trans;
            return query.ToList<periodical_action_transanction>();

        }

        public ModelResult SaveOrUpdatePeriodicalActionTransaction(periodical_action_transanction Transaction)
        {
            //validate !!!!
            
            if (Transaction.id == 0)
            {
                Program.Db.AddToperiodical_action_transanction(Transaction);
            }

            Program.Db.SaveChanges();

            return new ModelResult();
        }
    }
}
